package com.tingyuge.base.thread.wang.condition;

import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by xiaodao
 * date: 2019/12/19
 */
public class Test1 {
    private final static ReentrantLock lock = new ReentrantLock();
    private final static Condition condition = lock.newCondition();

    private static int data = 0;
    private static volatile boolean noUse = true;
    private static void buildData(){
        try {
            lock.lock();// 相当于 synchronized
           while (noUse){
               condition.wait();
           }
           data++;
            Optional.of("P:"+ data).ifPresent(System.out::println);
            TimeUnit.SECONDS.sleep(1);
            noUse= true;
            condition.signalAll();
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }
    private static void useData(){
        try {
            lock.lock();// 相当于 synchronized
            while (!noUse){
                condition.wait();
            }

//            TimeUnit.SECONDS.sleep(1);
            Optional.of("C:"+ data+"--"+Thread.currentThread().getName()).ifPresent(System.out::println);
            noUse= false;
            condition.signalAll();
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }
    public static void main(String[] args) {
        new Thread(()->{
            for(;;){
                buildData();
            }
        }).start();
        new Thread(()->{
            for(;;){
                useData();
            }
        }).start();
        new Thread(()->{
            for(;;){
                useData();
            }
        }).start();
    }
}
